var url=require('url');
var querystring=require('querystring');
var Config=require('./Config');
var readFile=require('./readFile');
var uuidUtil=require('./uuidUtil');

var const_room_page='./assets/html/room.html';

var users={};
var testroomid='chatRoom';
var chatRooms={
		chatRoom:{}
};


setInterval(clearInvalidResponse,1000*45);
function clearInvalidResponse(){
	var tempUsers={};
	for(var name in users){
		var user=users[name];
		if(typeof user==='object'){
			var time=new Date().getTime()-user.ActivationTime;
			if(time>1000*30){
				tempUsers[name]=users[name];
				delete users[name];
			}
		}
	}
	responsePersonInfo();
}

function isOnline(usersessionid){
	if(typeof users[usersessionid]==='object'){
		var user=users[usersessionid];
		var time=new Date().getTime()-user.ActivationTime;
		if(time>1000*30){
			delete users[usersessionid];
		}else{
			setTimeout(isOnline(usersessionid), 1000*30);
		}
	}
}

function getUserTempId(){
	return uuidUtil.createUUID();
}

function getResponseUser(tempUsers){
	var i=0;
	var responseMessage='';
	responseMessage+='[';
	for(var name in tempUsers){
		var user=tempUsers[name];
		if(i==0){
			responseMessage+='{';
		}else{
			responseMessage+=',{';
		}
		responseMessage+='\"username\":\"'+user.username+'\"';
		responseMessage+=',\"usersessionid\":\"'+name+'\"';
		responseMessage+='}';
		i++;
	}
	responseMessage+=']';
	return responseMessage;
}

function onRequestPersonsInfoOffLine(tempUsers){
	var responseMessage=getResponseUser(tempUsers);
	for(var name in users){
		var user=users[name];
		response.write(responseMessage);
		respone.end();
	}
}


function onRequestMessage(request,response){
	var querystr=url.parse(request.url).query;
	var message=querystring.parse(querystr)['message'];
	message=decodeURI(message);
	var usersessionid=querystring.parse(querystr)['usersessionid'];
	var user=users[usersessionid];
	
	
	function callback_sendMEssage(response,userMessage){
		userMessage=userMessage.replace(/\n/g,'<br/>');
		response.write(userMessage);
		response.end();
	}
	function sendMessage(response,userMessage,callback_sendMEssage){
		callback_sendMEssage(response,userMessage);
	}
	
	if(typeof user==='object'){
		var userChatRooms=user.chatRooms;
		if(typeof userChatRooms==='object'){
			for(var name in userChatRooms){
				var chatRoom=chatRooms[name];
				for(var nameTemp in chatRoom){
					var responseTemp=chatRoom[nameTemp].response;
					var userMessage='';
					userMessage+='{';
					userMessage+='\"username\":\"'+user.username+'\"';
					userMessage+=',\"message\":\"'+message+'\"';
					userMessage+='}';
					if(typeof response==='object'){
						//responseTemp.write(userMessage);
						//responseTemp.end();
						sendMessage(responseTemp,userMessage,callback_sendMEssage);
					}
				}
			}
		}
		response.write('success');
	}else{
		response.write('fail');
	}
	response.end();
}

function onRequestMessageFile(fields,response){
	var usersessionid=fields['usersessionid'];
	var user=users[usersessionid];
	if(typeof user==='object'){
		var userChatRooms=user.chatRooms;
		if(typeof userChatRooms==='object'){
			for(var name in userChatRooms){
				var chatRoom=chatRooms[name];
				for(var nameTemp in chatRoom){
					var responseTemp=chatRoom[nameTemp].response;
					var userMessage='';
					var filepath=fields.hdd_file_server_path;
					if(typeof filepath==='string'){
						filepath=filepath.substring(1,filepath.length);
					}
					userMessage+='{';
					userMessage+='\"username\":\"'+user.username+'\"';
					userMessage+=',\"filepath\":\"'+filepath+'\"';
					userMessage+='}';
					if(typeof responseTemp==='object'){
						responseTemp.write(userMessage);
						responseTemp.end();
					}
				}
			}
		}
		response.write('success');
	}else{
		response.write('fail');
	}
	response.end();
}


function savePersonResponse(request,response,callback){
	if(typeof callback==='function'){
		callback(request,response);
	}
}
function saveMessageResponse(request,response,callback){
	if(typeof callback==='function'){
		callback(request,response);
	}
}
function responsePersonInfo(){
	var responseMessage=getResponseUser(users);
	for(var name in users){
		var user=users[name];
		if(typeof user==='object'){
			if(typeof user.chatRooms[testroomid].response==='object'){
				if(typeof user.chatRooms[testroomid].response.write==='function'){
					user.chatRooms[testroomid].response.write(responseMessage);
					user.chatRooms[testroomid].response.end();
				}
			}
		}
	}
}

function enterRoom(request,response){
	var userInfo={chatRooms:{}};
	var obj={};
	var querystr=url.parse(request.url).query;
	var username=querystring.parse(querystr)['username'];
	var usersessionid=getUserTempId();
	var userChatRoom={};
	userChatRoom.zt='0';//0 表示刚刚进入房间,还有没进行推送,1表示该人一推送
	userChatRoom.ActivationTime=new Date().getTime();
	
	userInfo.username=username;
	userInfo.chatRooms[testroomid]=userChatRoom;
	
	users[usersessionid]=userInfo;
	var const_room_page_temp=const_room_page;
	
	function replace(response,file){
		file=file.replace(/<%=usersessionid %>/g,usersessionid);
		response.writeHead(200, {'Content-Type': Config.type.html});
		response.write(file, "binary");
        response.end();
	}
	readFile.readFile(const_room_page_temp,Config.type['html'],response,replace);
}

function comnetPersonsInfo(request,response){
	function callback(request,response){
		var querystr=url.parse(request.url).query;
		var usersessionid=querystring.parse(querystr)['usersessionid'];
		var flag=true;
		
		if(typeof users[usersessionid] ==='object'){
			var user=users[usersessionid].chatRooms[testroomid];
			var zt=users[usersessionid].chatRooms[testroomid].zt;
			if(zt=='0'){
				users[usersessionid].chatRooms[testroomid].zt='1';
				flag=false;
			}else if(zt=='1'){
				
			}
			users[usersessionid].chatRooms[testroomid].response=response;
			if(!flag){
				responsePersonInfo();
			}
		}
	}
	savePersonResponse(request,response,callback);
}
function comnetMessageInfo(request,response){
	function callback(request,response){
		var querystr=url.parse(request.url).query;
		var usersessionid=querystring.parse(querystr)['usersessionid'];
		var message=querystring.parse(querystr).message;
		
		var userInfo={};
		userInfo.response=response;
		chatRooms[testroomid][usersessionid]=userInfo;
		
	}
	saveMessageResponse(request,response,callback);
}
function activateOnline(request,response){
	var querystr=url.parse(request.url).query;
	var usersessionid=querystring.parse(querystr)['usersessionid'];
	if(typeof users[usersessionid]==='object'){
		users[usersessionid].ActivationTime=new Date().getTime();
		response.write('updateSuccess');
		response.end();
	}else{
		response.write('off-line');
		response.end();
	}
}
function sendMessage(request,response){
	onRequestMessage(request,response);
}
exports.enterRoom=enterRoom;
exports.comnetPersonsInfo=comnetPersonsInfo;
exports.activateOnline=activateOnline;
exports.comnetMessageInfo=comnetMessageInfo;
exports.sendMessage=sendMessage;
exports.onRequestMessageFile=onRequestMessageFile;